package com.villaday.idf.activity;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.AppContext;
import com.villaday.idf.R;
import com.villaday.idf.adapter3.SleepAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.CircleTextView;
import com.villaday.idf.custom.CustomViewPager;
import com.villaday.idf.custom.LoadDialog;
import com.villaday.idf.custom.LoadingSaveDialog;
import com.villaday.idf.custom.NavView;
import com.villaday.idf.custom.pop.SleepPop;

import com.villaday.idf.fragment3.SleepFragment;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model3.PosterEntity;
import com.villaday.idf.model3.SleepEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DownUtil;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;
import com.yarolegovich.discretescrollview.DiscreteScrollView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class SleepActivity extends BaseActivity {


    @BindView(R.id.toolbar_iconBack)
    ImageButton toolbarIconBack;
    @BindView(R.id.toolbar_iconTitle)
    TextView toolbarIconTitle;
    @BindView(R.id.toolbar_iconNext)
    ImageButton toolbarIconNext;
    @BindView(R.id.toolbar_iconCartDot)
    CircleTextView toolbarIconCartDot;
    @BindView(R.id.toolbar_iconLine)
    View toolbarIconLine;
    @BindView(R.id.toolbar_icon)
    Toolbar toolbarIcon;
    @BindView(R.id.dsv_picker)
    DiscreteScrollView dsvPicker;
    @BindView(R.id.tv_sleep_time)
    TextView tvSleepTime;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_sleep_notify)
    TextView tvSleepNotify;
    @BindView(R.id.vw_l_1)
    View vwL1;
    @BindView(R.id.tv_before)
    TextView tvBefore;
    @BindView(R.id.rv_sleep)
    RecyclerView rvSleep;
    @BindView(R.id.tv_sleep_more)
    TextView tvSleepMore;
    @BindView(R.id.tv_sleep_vip)
    TextView tvSleepVip;
    @BindView(R.id.tv_sleep_svip)
    TextView tvSleepSvip;
    @BindView(R.id.nv_sleep)
    NavView nvSleep;
    @BindView(R.id.tv_sleep_num)
    TextView tvSleepNum;
    @BindView(R.id.rv_sleep_top)
    RecyclerView rvSleepTop;
    @BindView(R.id.vp_sleep)
    CustomViewPager vpSleep;


    private SleepAdapter mSleepAdapter;
    private float mOldY = 0;
    private float mNewY = 0;
    private float mOldX = 0;
    private float mNewX = 0;
    private int mScrollY = 10;//控制手指移动距离
    private int position = 0;

    private List<SleepEntity.BodyBean.TemplateListBean> mTemplateList;
    private List<SleepEntity.BodyBean.PreviousListBean> mPreviousList;
    private LoadDialog mLoadDialog;
    private SleepEntity.BodyBean mBody;
    private int mNumber = -1;
    private PosterEntity.BodyBean mPosterBody;
    private SleepPop mSleepPop;
    private int start = 0;
    private int end = 5;
    private static String pathString;


    @Override
    protected int getViewResId() {
        return R.layout.activity_sleep;
    }


    @Override
    protected void init() {
        super.init();
        ToolBarUtil.initToolBar(toolbarIcon, "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //是否是Vip
        RefreshtokenEntity.BodyBean roleInfo = SharedPreferencesUtil.getRoleInfo(this);
        if (roleInfo != null) {
            if ("1".equals(roleInfo.getMember().getType())) {//vip
                tvSleepVip.setVisibility(View.VISIBLE);
                tvSleepSvip.setVisibility(View.GONE);
            } else if ("2".equals(roleInfo.getMember().getType())) {//sVip
                tvSleepVip.setVisibility(View.VISIBLE);
                tvSleepSvip.setVisibility(View.VISIBLE);
            } else {
                tvSleepVip.setVisibility(View.GONE);
                tvSleepSvip.setVisibility(View.GONE);
            }
        }
        initAdapter();
        getDetails();
    }

    private void initVp() {
        vpSleep.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
        vpSleep.setOffscreenPageLimit(1);
        vpSleep.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
                LogUtil.jLog().e(i + "   " + v + "   " + i1);
                if (i + v > i + 0.5) {
                    position = i + 1;
                    nvSleep.setCurrentItem(position);
                } else {
                    position = i;
                    nvSleep.setCurrentItem(position);
                }
                mNumber = mTemplateList.get(position).getNumber();
                try {
                    if (v == 0) {
                        for (int j = 0; j < mTemplateList.size(); j++) {
                            View childAt = vpSleep.getChildAt(j);
                            if (i == j) {
                                childAt.findViewById(R.id.vw_sleep).setVisibility(View.GONE);
                            } else {
                                childAt.findViewById(R.id.vw_sleep).setVisibility(View.VISIBLE);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onPageSelected(int i) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });

//        vpSleep.setPageTransformer(true, new CoverModeTransformer(vpSleep));
    }


    class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return SleepFragment.instance(position, mTemplateList.get(position).getPoster());
        }

        @Override
        public int getCount() {
            return mTemplateList.size();
        }
    }


    private void getDetails() {
        showDialog();
        OkHttpUtil.getJSON(this, Constant.URL.newest, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    dismissLoading();
                    SleepEntity sleepEntity = new Gson().fromJson(json, SleepEntity.class);
                    if (sleepEntity.getCode().equals(Constant.Strings.SUC)) {
                        mBody = sleepEntity.getBody();
                        tvType.setText(mBody.getContext().replace("<br>", "\n"));
                        tvSleepTime.setText("* 活动有效期至：" + mBody.getEndTime());
                        tvSleepNotify.setText(mBody.getTips());
                        toolbarIconTitle.setText(mBody.getName());
                        mTemplateList = mBody.getTemplateList();
                        nvSleep.setCount(mTemplateList.size());
                        tvSleepNum.setText(mBody.getPhaseNumber() + "");
                        PhoneUtil.setExternalFont(SleepActivity.this, tvSleepNum, true);
                        initVp();
                        mNumber = mTemplateList.get(0).getNumber();
                        mPreviousList = mBody.getPreviousList();
                        List<SleepEntity.BodyBean.PreviousListBean> previousListItem = new ArrayList<>();
                        if (mPreviousList.size() > 4) {
                            for (int i = start; i < mPreviousList.size(); i++) {
                                if (i < end - 1) {
                                    previousListItem.add(mPreviousList.get(i));
                                }
                            }
                            start = end;
                            end = end + 4;
                            tvSleepMore.setVisibility(View.VISIBLE);
                        } else {
                            previousListItem = mPreviousList;
                            tvSleepMore.setVisibility(View.GONE);
                        }
                        mSleepAdapter.setData(previousListItem);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    private void initAdapter() {
        rvSleep.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mSleepAdapter = new SleepAdapter(this);
        rvSleep.setAdapter(mSleepAdapter);
    }

    private void dismissLoading() {
        if (mLoadDialog != null) {
            mLoadDialog.dismiss();
        }
    }

    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (mLoadDialog == null) {
            mLoadDialog = LoadDialog.newInstance("加载中");
        }
        mLoadDialog.show(getSupportFragmentManager(), "loading");
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.tv_sleep_fins,R.id.tv_sleep_vip, R.id.tv_sleep_svip})
    public void btnOnclick(View view) {
        showDialog();
        if (mBody != null) {
            HashMap<String, String> hashMap = new HashMap<>();
            switch (view.getId()) {
                case R.id.tv_sleep_vip:
                    hashMap.put("activityId", mBody.getId());
                    hashMap.put("number", mNumber + "");
                    hashMap.put("upgrade", "1");
                    break;
                case R.id.tv_sleep_svip:
                    hashMap.put("activityId", mBody.getId());
                    hashMap.put("number", mNumber + "");
                    hashMap.put("upgrade", "2");
                    break;
                case R.id.tv_sleep_fins:
                    hashMap.put("activityId", mBody.getId());
                    hashMap.put("number", mNumber + "");
                    hashMap.put("upgrade", "3");
                    break;
            }
//            LogUtil.jLog().e(new Gson().toJson(hashMap));
            OkHttpUtil.getJSON(this, Constant.URL.poster, hashMap, new OkHttpUtil.OnDataListener() {
                @Override
                public void onResponse(String url, String json) {
                    if (!TextUtils.isEmpty(json)) {
                        LogUtil.jLog().e(json);
                        dismissLoading();
                        PosterEntity posterEntity = new Gson().fromJson(json, PosterEntity.class);
                        if (posterEntity.getCode().equals(Constant.Strings.SUC)) {
                            mPosterBody = posterEntity.getBody();
                            final List<String> imgList = new ArrayList<>();
                            imgList.add(mPosterBody.getPoster());
                            mSleepPop = new SleepPop(SleepActivity.this, mPosterBody.getPoster());
                            mSleepPop.setOnBtnClickListener(new SleepPop.OnBtnClickListener() {
                                @Override
                                public void onBtnClick(View view) {
                                    switch (view.getId()) {
                                        case R.id.ll_wx:
                                            showDialog();
                                            ShareUtilse.shareImage(SleepActivity.this, 0, imgList, imgList.get(imgList.size() - 1),"");
                                            mSleepPop.getPopupWindow().dismiss();
                                            break;
                                        case R.id.ll_pyq:
                                            showDialog();
                                            ShareUtilse.shareImage(SleepActivity.this, 1, imgList, imgList.get(imgList.size() - 1),"");
                                            mSleepPop.getPopupWindow().dismiss();
                                            break;
                                        case R.id.ll_save:
                                            LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("保存中");
                                            loadingDialog.show(getFragmentManager(), "0");
                                            DownUtil.saveImageForRecursive(SleepActivity.this, imgList, 1, loadingDialog);
                                            break;
                                    }

                                }
                            });
                            mSleepPop.showPopupWindow();
                        } else {
                            ToastUtil.initToast(getApplicationContext(), posterEntity.getMsg());
                        }
                    }
                }

                @Override
                public void onFailure(String url, String error) {
                    dismissLoading();
                }
            });
        } else {
            ToastUtil.initToast(getApplicationContext(), "暂时不能点击");
        }

    }


    @Override
    public void onResume() {
        super.onResume();
        if (mNumber != -1) {
            dismissLoading();
        }

//        if (!TextUtils.isEmpty(pathString)) {
//            LogUtil.jLog().e("删除图片：" + pathString);
//            ShareUtilse.deletePic(this, pathString);
//            pathString = "";
//        }

    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:
                mNewY = ev.getY();
                mNewX = ev.getX();
                return super.dispatchTouchEvent(ev);
            case MotionEvent.ACTION_DOWN:
                mOldY = ev.getY();
                mOldX = ev.getX();
                return super.dispatchTouchEvent(ev);
            case MotionEvent.ACTION_UP:
//                LogUtil.jLog().e("抬起" + mNewX + "   " + mOldX + "  " + "     " + mNewY + "   " + mOldY + "   " + PhoneUtil.dp2px(this, 5));
                if ((Math.abs(mNewX - mOldX) < mScrollY && Math.abs(mNewY - mOldY) < mScrollY) || (mNewY == 0 && mNewX == 0)) {
                } else {
                    if (mOldY > mNewY && mNewY != 0 && (mOldY - mNewY > mScrollY)) {//向上滑(加载)
                        if (PhoneUtil.isVisible(this, tvSleepMore) && mPreviousList != null) {
                            if (start >= mPreviousList.size()) {
                                tvSleepMore.setVisibility(View.GONE);
                            } else {
                                List<SleepEntity.BodyBean.PreviousListBean> previousListItem = new ArrayList<>();
                                for (int i = start; i < mPreviousList.size(); i++) {
                                    if (i < end) {
                                        previousListItem.add(mPreviousList.get(i));
                                    }
                                }
                                mSleepAdapter.setData(previousListItem);
                                start = end;
                                end = end + 4;
                                tvSleepMore.setVisibility(View.VISIBLE);
                                if (start >= mPreviousList.size()) {
                                    tvSleepMore.setVisibility(View.GONE);
                                }
                            }
                        }
                    } else if (mOldY < mNewY && mNewY != 0 && (mNewY - mOldY > mScrollY)) {//向下滑动

                    }
                    mNewY = 0;
                    mNewX = 0;
                }
                return super.dispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * @param flag 0分享给微信好友  1分享到朋友圈
     */
    public static void shareImage(final Context context, final int flag, final List<String> images, final String isHightWXNeedShare) {
        final List<File> files = new ArrayList<>();
        //判断是否安装微信，如果没有安装微信 又没有判断就直达微信分享是会挂掉的
        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.ID.WeChat_APP_ID, true);
        api.registerApp(Constant.ID.WeChat_APP_ID);
        if (!api.isWXAppInstalled()) {//未安装微信
            ToastUtil.initToast(context, "您未安装微信");

        } else {


            new Thread(new Runnable() {
                @Override
                public void run() {
                    //这一步一定要clear,不然分享了朋友圈马上分享好友图片就会翻倍
                    files.clear();

                    try {
                        Intent intent = new Intent();
                        ComponentName comp;
                        if (flag == 0) {//flag 0分享给微信好友
                            for (int i = 0; i < images.size(); i++) {
                                File file = saveImageToSdCard(context, images.get(i), false);
                                files.add(file);
                            }
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                            ArrayList<Uri> imageUris = new ArrayList<Uri>();
                            for (File f : files) {
                                pathString = f.getAbsolutePath();
                                imageUris.add(Uri.fromFile(f));
                            }
                            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                        } else {//1分享到朋友圈
                            if (AppContext.isHightWX) {
                                File file = saveImageToSdCard(context, isHightWXNeedShare, false);
                                pathString = file.getAbsolutePath();
                                intent.setAction(Intent.ACTION_SEND);
                                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                            } else {
                                for (int i = 0; i < images.size(); i++) {
                                    File file = saveImageToSdCard(context, images.get(i), false);
                                    pathString = file.getAbsolutePath();
                                    files.add(file);
                                }
                                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                                ArrayList<Uri> imageUris = new ArrayList<Uri>();
                                for (File f : files) {
                                    imageUris.add(Uri.fromFile(f));
                                }
                                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                            }
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                            intent.putExtra("Kdescription", "分享朋友圈的图片说明");
                        }
                        intent.setComponent(comp);
                        intent.setType("image/*");
                        context.startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }).start();
        }
    }


    //根据网络图片url路径保存到本地
    public static File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));//path_export是你导出的文件路径
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {

            return file;
        } else {
            return null;
        }
    }


    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = "adf_share_" + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        String imageFileName = "adf_share_" + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }
}
